<template>
  <div>
    <div class="search-title">查询条件</div>
    <div class="search-box">
      <a-form-model :model="searchForm" layout="inline" ref="searchForm" class="searchForm">
        <a-form-model-item prop="searchValue" label="功能名称">
          <a-input v-model="searchForm.searchFunctionName" placeholder="请输入功能名称">
            <a-icon slot="prefix" type="search" />
          </a-input>
        </a-form-model-item>
        <a-form-model-item class="searchButton" >
          <a-button type="primary" @click="getFunctionListByInput">查询</a-button>
          <a-button type="default" @click="restSearch('searchForm')">重置</a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
    <div class="table-operation">
      <a-button type="primary" @click="addFunction" icon="plus" v-if="QX.add">新增</a-button>
    </div>
    <a-table
      :scroll="{x:830,y: this.$getViewportSize().height-260 }"
      :columns="columns"
      :data-source="dataList"
      :pagination="false"
      :loading="loading"
      :expanded-row-keys.sync="expandedRowKeys"
      :expandIcon="expandIcon"
      :expandIconColumnIndex="1"
      rowKey="function_id"
    >
      <span slot="isEffective" slot-scope="text,record">
          <a-switch v-model="record.is_effective === '1'" :disabled="!QX.edit" checked-children="有效" un-checked-children="无效" @click="isEffectiveClick(record)">
            <a-icon slot="checkedChildren" type="check" />
            <a-icon slot="unCheckedChildren" type="close" />
          </a-switch>
        </span>
      <span slot="iconName" slot-scope="text,record">
        <i v-if="record.ico_name" class="iconfont" :class="'icon-'+record.ico_name"></i>
        </span>
      <span slot="app_func" slot-scope="text,record">
       <span v-if="text=='1'"><a-tag color="blue">是</a-tag></span>
         <span v-else-if="text=='0'"><a-tag>否</a-tag></span>
        </span>
      <span slot="is_alarm_func" slot-scope="text,record">
       <span v-if="text=='1'"><a-tag color="blue">是</a-tag></span>
         <span v-else-if="text=='0'"><a-tag>否</a-tag></span>
        </span>
      <span slot="permis" slot-scope="text,record">
        <TableTootip :content="text"></TableTootip>
      </span>
      <span slot="function_url" slot-scope="text,record">
        <TableTootip :content="text"></TableTootip>
      </span>

      <span slot="action" slot-scope="text,record">
          <a @click="editFunc(record)" v-if="QX.edit"><a-icon class="iconBtn" type="edit"/>编辑</a>
          <a-divider v-if="QX.edit && QX.delete" type="vertical"/>
          <a-popconfirm
            title="确认是否删除？"
            ok-text="是"
            cancel-text="否"
            @confirm="removeFunc(record)"
          >
            <a v-if="QX.delete"><a-icon class="iconBtn" type="delete"/>删除</a>
          </a-popconfirm>
        </span>
    </a-table>
    <a-drawer
      :closable="true"
      :title="title"
      :visible="visible"
      @close="visible=!visible"
      :width="1050"
    >
      <a-spin class="submitLoading" :spinning="submitLoading">
        <a-form-model :model="form" :rules="rules" ref="form" :label-col="labelCol" :wrapper-col="wrapperCol" class="lay-drawer-form">
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="功能代号" prop="permis">
                <a-input v-model="form.permis" :maxLength="20" oninput="if (value.charCodeAt(value.length-1)>65280 && value.charCodeAt(value.length-1)<65375)value=value.substr(0,value.length-1)"
                         placeholder="请输入功能代号" :disabled="permisDisable" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="功能名称" prop="functionName">
                <a-input v-model="form.functionName" :maxLength="25" placeholder="请输入功能名称" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="功能级别" prop="functionLevel">
                <a-select placeholder="请选择功能级别" v-model="form.functionLevel" style="width: 380px">
                  <a-select-option v-for="d in selectDatas" :key="d.value" :value="d.value">{{ d.text }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="功能排序" prop="sortNo">
                <a-input v-model.number="form.sortNo" :maxLength="3" oninput="if (value.charCodeAt(value.length-1)>65280 && value.charCodeAt(value.length-1)<65375)value=value.substr(0,value.length-1)"
                         placeholder="请输入功能排序" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="功能图标" prop="icoName">
                <a-input v-model="form.icoName" :maxLength="40" placeholder="请输入功能图标" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="是否有效" prop="isEffective">
                <a-radio-group v-model="form.isEffective">
                  <a-radio value="1">有效</a-radio>
                  <a-radio value="0">无效</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="所属功能" prop="parentId">
                <a-tree-select v-model="form.parentId" :treeData="menuTree" :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" placeholder="请选择所属功能"
                               tree-default-expand-all style="width: 380px">
                </a-tree-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="功能地址" prop="functionUrl">
                <a-input v-model="form.functionUrl" :maxLength="40" oninput="if (value.charCodeAt(value.length-1)>65280 && value.charCodeAt(value.length-1)<65375)value=value.substr(0,value.length-1)"
                         placeholder="请输入功能地址" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="APP功能" prop="appFunc">
                <a-radio-group v-model="form.appFunc">
                  <a-radio value="1">是</a-radio>
                  <a-radio value="0">否</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="告警模块" prop="isAlarmFunc">
                <a-radio-group v-model="form.isAlarmFunc">
                  <a-radio value="1">是</a-radio>
                  <a-radio value="0">否</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <div
          :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '8px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }">
          <a-button
            type="default"
            @click="visible=!visible"
          >
            取消
          </a-button>
          <a-button
            type="primary"
            @click="submitForm"
          >
            确认
          </a-button>
        </div>
      </a-spin>
    </a-drawer>
  </div>
</template>

<script>
  import { req } from "../../../api/axiosFun";
  import preventBack from 'vue-prevent-browser-back';
  import TableTootip from '../../../components/TableTootip.vue'
  export default {
    name: "Function",
    mixins: [preventBack],//注入
    components:{
      TableTootip
    },
    data() {
      let validateUrl = (rule, value, callback) => {
        var isMob = /^\/[a-zA-Z]+$/;
        if (value) {
          if (!isMob.test(value)) {
            callback(new Error('功能地址格式错误'));
          }
        }
        callback();
      };
      return {
        QX: {},
        disabled: false,
        labelCol: { span: 5 },
        wrapperCol: { span: 19 },
        rules: {
          functionName: [
            { required: true, message: '请输入功能名称', trigger: 'blur' },
          ],
          functionLevel: [
            { required: true, message: '请选择功能级别', trigger: 'change' },
          ],
          isEffective: [
            { required: true, message: '请选择是否有效', trigger: 'change' },
          ],
          parentId: [
            { required: true, message: '请选择所属功能', trigger: 'change' },
          ],
          functionUrl: [
            { validator: validateUrl, trigger: 'blur' },
          ],
          sortNo: [
            { type: "number", message: '请输入数字', trigger: 'blur' },
          ],
          permis: [
            { required: true, message: '请输入功能代号', trigger: 'blur' },
          ],
        },
        selectDatas: [],
        expandedKeys: [],
        autoExpandParent: true,
        menuList: [],
        title: '',
        menuTree: [],
        permisDisable: false,
        form: {
          functionId: '',
          functionName: '',
          functionLevel: undefined,
          sortNo: '',
          icoName: '',
          isEffective: '1',
          functionUrl: '',
          parentId: undefined,
          permis: '',
          isAlarmFunc: '0',
          appFunc: '0'
        },
        searchForm: {
          searchFunctionName: '',
          functionId: '',
        },
        treeData: [],
        visible: false,
        dataList: [],
        expandedRowKeys:[],
        columns,
        loading: false,
        submitLoading: false,
        ops: {
          vuescroll: {},
          scrollPanel: {},
          rail: {
            keepShow: true
          },
          bar: {
            hoverStyle: true,
            onlyShowBarOnScroll: false, //是否只有滚动的时候才显示滚动条
            background: "#F5F5F5",//滚动条颜色
            opacity: 0,//滚动条透明度
            "overflow-x": "hidden",
            "overflow-y": "auto"
          }
        },
        autoHeight: 500,
        solidHeight: 500,
      }
    },
    watch: {
      visible(newVal, oldVal) {
        if (!newVal) {
          this.restForm('form');
          this.form.functionId = ''
        }
      }
    },
    created() {
      this.autoHeight = this.$getViewportSize().height - 150
      this.solidHeight = this.$getViewportSize().height - 80
    },
    mounted() {
      this.getMenuTree();
      this.getFunctionList();
      this.getMenuList();
    },
    methods: {
      expandIcon(props) {
        if (props.record.children&&props.record.children.length) {
          if (props.expanded) {
            return (
              <span
                class="table-icon"
                onClick={(e) => {
                  props.onExpand(props.record, e);
                }}
              >
                <a-icon type="down" />
              </span>
            );
          } else {
            return (
              <span
                class="table-icon"
                onClick={(e) => {
                  props.onExpand(props.record, e);
                }}
              >
                <a-icon type="right" />
              </span>
            );
          }
        } else {//无数据-图标
          return <span style="margin-right:19px"></span>;
        }
      },
      /* 添加功能菜单 */
      addFunction() {
        this.form = this.$options.data().form
        this.disabled = false;
        this.visible = true;
        this.title = '新增功能菜单';
        this.permisDisable = false;
        //菜单下拉框
        this.getMenuTree();
      },
      /* 编辑功能菜单 */
      editFunc(record) {
        this.permisDisable = true;
        this.loading = true
        /*菜单下拉框*/
        this.getMenuTree();
        req('post', '/function/findFunctionById', {
          functionId: record.function_id
        }).then(res => {
          this.loading = false
          if (res.result === 'success') {
            this.disabled = true;
            this.title = '修改功能菜单';
            this.visible = true;
            this.$nextTick(()=>{
              this.form.functionId = res.data.function_id;
              this.form.functionName = res.data.function_name;
              this.form.functionLevel = res.data.function_level;
              this.form.sortNo = res.data.sort_no;
              this.form.icoName = res.data.ico_name;
              this.form.isEffective = res.data.is_effective;
              this.form.functionUrl = res.data.function_url;
              this.form.parentId = res.data.parent_id;
              this.form.permis = res.data.permis;
              this.form.isAlarmFunc = res.data.is_alarm_func;
              this.form.appFunc = res.data.app_func;
            })
          }
        });
      },
      /* 启用/禁用 功能菜单 */
      isEffectiveClick(record) {
        var that = this;
        let functionName = record.function_name;
        let isEffective = record.is_effective;
        let content = isEffective === '1' ? '确认要禁用\"' + functionName + '\"菜单吗？' : '确认要启用\"' + functionName + '\"菜单吗？';
        this.$confirm({
          title: '警告',
          content: content,
          onOk() {
            req("post", '/function/editEffective', {
              isEffective: isEffective === '1' ? '0' : '1',
              functionId: record.function_id
            }).then(res => {
              if (res.result === 'success') {
                if (isEffective === '1') {
                  record.is_effective = '0';
                } else if (isEffective === '0') {
                  record.is_effective = '1';
                }
                that.$message.success(res.message);
              }
            });
          },
          onCancel() {
          },
        });
      },
      /* 保存or修改菜单信息 */
      submitForm() {
        this.$refs.form.validate(valid => {
          if (valid) {
            const url = this.title === '修改功能菜单' ? 'editFunction' : 'addFunction';
            this.submitLoading = true
            req("post", `/function/${url}`, this.form).then(res => {
              if (res.result === 'success') {
                this.visible = false;
                this.getFunctionList();
                this.getMenuTree();
                this.$message.success(res.message);
              }
              this.submitLoading = false
            });
          }
        });
      },
      /* 菜单树 and 表单下拉数据*/
      getMenuTree() {
        req('post', '/function/leftMenuList', {})
          .then(res => {
            if (res.result === 'success') {
              this.treeData = res.menuList;
              this.expandedKeys = [res.menuList[0].functionId];
              //表单下拉数据
              let treeData = this.treeData;
              let menuTree = [];
              menuTree.push({ value: 0, label: '根目录' })
              treeData.forEach((tree, index) => {
                //去除主页菜单
                if (tree.function_id == 1) {
                  return;
                }
                let func1 = { value: tree.function_id, label: tree.function_name };
                menuTree.push(func1);
              });
              this.menuTree = menuTree;
            }
          });
      },
      /* 功能菜单列表  */
      getFunctionList() {
        this.loading = true;
        req("post", `/function/getFunctionListPage`, this.searchForm)
          .then(res => {
            if (res.result === 'success') {
              this.dataList = res.data;
              this.dataList.forEach(item=>{
                if(item.ico_name==''){
                  item.ico_name = ' '
                }
                if(item.children.length){
                  item.children.forEach(child=>{
                    if(child.ico_name==''){
                      child.ico_name = ' '
                    }
                  })
                }
              })
              this.QX = res.QX;
              if (!this.QX.edit && !this.QX.delete) {
                this.hideAction();
              } else if (columns[columns.length - 1].title != '操作') {
                columns.push(actionShow);
              }
            }
            this.loading = false;
          }).catch(error => {
            this.loading = false;
            this.hideAction();
          });
      },
      /*搜索按钮触发*/
      getFunctionListByInput() {
        this.searchForm.functionId = '';
        this.pageIndex = 1
        this.getFunctionList();
      },

      /* 重置查询 */
      restSearch(form) {
        this.restForm(form);
        this.searchForm.searchFunctionName = '';
        this.searchForm.functionId = '';
        this.pageIndex = 1
        this.getFunctionList();
        this.getMenuTree();
      },
      /* 重置表单 */
      restForm(form) {
        this.$refs[form].resetFields();
      },
      /* 点击菜单树节点触发 */
      onSelect(selectedKeys, info) {
        if (selectedKeys && selectedKeys.length) {
          this.searchForm.functionId = selectedKeys[0];
          this.searchForm.searchFunctionName = '';
          this.getFunctionList();
        }
      },
      /* 删除菜单 */
      removeFunc(record) {
        this.loading = true
        req("post", '/function/removeFunc', {
          functionId: record.function_id
        }).then(res => {
          this.loading = false
          if (res.result === 'success') {
            this.$message.success(res.message);
            this.searchForm.searchFunctionName = '';
            this.searchForm.functionId = '';
            this.getFunctionList();
            this.getMenuTree();
          }
        });
      },
      //生成菜单级别下拉框
      getMenuList() {
        req("post", '/dict/getDictItemByNo', { dicNo: 'menu_level' })
          .then(res => {
            if (res.result === 'success') {
              this.selectDatas = [];
              res.data.forEach((r) => {
                this.selectDatas.push({
                  value: parseInt(r.dicValue),
                  text: r.dicDisplayName
                });
              });
            }
          }
          );
      },
      /*无所有行操作权限时,隐藏操作栏*/
      hideAction() {
        if (columns[columns.length - 1].title == '操作') {
          columns.splice(columns.length - 1, 1)
        }
      }
    }
  }
  const actionShow = {
    align: 'center',
    title: '操作',
    width: 150,
    fixed: 'right',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
  };
  const columns = [
    {
      title: '序号',
      width: '40px',
      fixed: 'left',
      align:'center',
      customRender: (text, record, index) => `${index + 1}`,
    },
    {
      title: '功能名称',
      dataIndex: 'function_name',
      key: 'function_name',
      align:'left',
      width: 130,
    },
    {
      title: '功能代号',
      dataIndex: 'permis',
      key: 'permis',
      align:'center',
      width: 140,
      scopedSlots: { customRender: 'permis' },
    },
    {
      title: '功能级别',
      dataIndex: 'function_level_name',
      key: 'function_level_name',
      align:'center',
      width: 68
    },
    {
      title: '功能排序',
      dataIndex: 'sort_no',
      key: 'sort_no',
      align:'center',
      width: 68
    },

    {
      title: '功能图标',
      dataIndex: 'ico_name',
      key: 'ico_name',
      align: 'center',
      scopedSlots: { customRender: 'iconName' },
      width: 68
    },
    {
      title: '是否有效',
      dataIndex: 'is_effective',
      key: 'is_effective',
      align:'center',
      scopedSlots: { customRender: 'isEffective' },
      width: 70
    },
    {
      title: '功能地址',
      dataIndex: 'function_url',
      key: 'function_url',
      align:'left',
      width: 140,
      scopedSlots: { customRender: 'function_url' },
    },
    {
      title: '所属功能',
      dataIndex: 'parent_name',
      key: 'parent_name',
      align:'center',
      width: 70
    },
    {
      title: 'APP功能',
      dataIndex: 'app_func',
      key: 'app_func',
      align:'center',
      scopedSlots: {customRender: 'app_func'},
      width: 68
    },
    {
      title: '告警模块',
      dataIndex: 'is_alarm_func',
      key: 'is_alarm_func',
      align:'center',
      scopedSlots: {customRender: 'is_alarm_func'},
      width: 68
    },
    {
      align: 'center',
      title: '操作',
      width: 130,
      fixed: 'right',
      dataIndex: 'action',
      key: 'action',
      scopedSlots: { customRender: 'action' },
    },
  ];

</script>

<style scoped>
  @import "../../../assets/css/maincss.css";
</style>
